package com.naiterui.ehp.bs.esign.api.scca.util;/**
 * @author guoyongxiang
 * @date 2021/3/1 18:11
 * @since 1.0.0
 */

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/**
 * BC证书工具类
 *
 * @author guoyongxiang
 * @version 1.0.0
 * @date 2021/3/1 18:11
 **/
@Slf4j
public class BcCertUtil {

    static {
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            log.info("security provider BC not found");
            Security.addProvider(new BouncyCastleProvider());
        }

    }

    /**
     * 根据文件路径获取证书信息
     *
     * @param filePath
     * @return
     * @throws CertificateException
     * @throws NoSuchProviderException
     * @throws FileNotFoundException
     */
    public static X509Certificate getCertInfoByFilePath(String filePath) throws CertificateException, NoSuchProviderException, FileNotFoundException {
        FileInputStream in = new FileInputStream(filePath);
        return getCertInfo(in);
    }

    /**
     * 根据证书BASE64获取证书信息
     *
     * @param base64
     * @return
     * @throws CertificateException
     * @throws NoSuchProviderException
     */
    public static X509Certificate getCertInfoByBase64(String base64) throws CertificateException, NoSuchProviderException {
        ByteArrayInputStream in = new ByteArrayInputStream(Base64.getDecoder().decode(base64));
        return getCertInfo(in);
    }

    private static X509Certificate getCertInfo(InputStream in) throws CertificateException, NoSuchProviderException {
        CertificateFactory cf = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
        X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
        return cert;
    }
}
